package cn.fl.risk.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.condition.RskAppoRecQueryCondition;
import cn.fl.risk.service.IRskAppoRecService;
import cn.fl.risk.vo.RskAppoRecVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 催收预约表 控制层
 */
@Controller
@RequestMapping("/risk/rskAppoRec")
public class RskAppoRecController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(RskAppoRecController.class);

	/**
	 * RskAppoRec 服务层BEAN
	 */
	@Autowired
	private IRskAppoRecService rskAppoRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载RskAppoRec列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskAppoRec/rskAppoRecList");
		return mav;
	}

	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载RskAppoRec Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskAppoRec/rskAppoRecModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载RskAppoRec Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskAppoRec/rskAppoRecModify");
		//this.prepare(request,mav);

		String id=request.getParameter("id");
		RskAppoRecVO rskAppoRecVO = this.rskAppoRecService.selectById(Long.valueOf(id));
		mav.addObject("rskAppoRecVO", rskAppoRecVO);
		return mav;
	}

	//加载数据字典数据、传值等 ？
	public void prepare(HttpServletRequest request,ModelAndView mav){

	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initRskAppoRecList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		RskAppoRecQueryCondition qc = new RskAppoRecQueryCondition();
		//TODO 设置查询条件？
		String searchName = request.getParameter("searchName");
		if (StringUtils.isNotEmpty(searchName)) {

		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initRskAppoRecList", "初始化RskAppoRec列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.rskAppoRecService.searchListPage(page);
		List<RskAppoRecVO> list = (List<RskAppoRecVO>) pager.getResultList();
		ListPageVO<RskAppoRecVO> listPage = new ListPageVO<RskAppoRecVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeRskAppoRecByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeRskAppoRecByIds", "删除RskAppoRec数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			boolean success = this.rskAppoRecService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeRskAppoRecByIds", "删除RskAppoRec数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeRskAppoRecByIds", "删除RskAppoRec数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeRskAppoRecByIds", "删除RskAppoRec数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeRskAppoRecByIds", "删除RskAppoRec数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getRskAppoRecById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getRskAppoRecById", "获取RskAppoRec数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			RskAppoRecVO vo = this.rskAppoRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getRskAppoRecById", "获取RskAppoRec数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getRskAppoRecById", "获取RskAppoRec数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getRskAppoRecById", "获取RskAppoRec数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getRskAppoRecById", "获取RskAppoRec数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addRskAppoRec(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "预约成功");
		List<RskAppoRecVO> voList = null;
		try {
			voList = this.getRequestParamForAppoRec(request);//获取参数
			if(CollectionUtils.isEmpty(voList)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+"预约失败");
			}else{
				boolean success = this.rskAppoRecService.add(voList);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
					BaseLogUtils.info(logger, "addRskAppoRec", "新增RskAppoRec数据失败.DATA:"+JSONObject.toJSONString(voList), CurrentThreadContext.getCurrentUserName());
					return result;
				}
				BaseLogUtils.info(logger, "addRskAppoRec", "新增RskAppoRec数据成功,DATA:"+JSONObject.toJSONString(voList), CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addRskAppoRec", "新增RskAppoRec数据失败.DATA:"+JSONObject.toJSONString(voList)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addRskAppoRec", "新增RskAppoRec数据失败,系统错误.DATA:"+JSONObject.toJSONString(voList)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyRskAppoRec(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		RskAppoRecVO entity = null;
		try {
			entity = this.getRequestParamForRskAppoRec(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyRskAppoRec", "修改RskAppoRec信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.rskAppoRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyRskAppoRec", "修改RskAppoRec数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyRskAppoRec", "修改RskAppoRec数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyRskAppoRec", "修改RskAppoRec数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyRskAppoRec", "修改RskAppoRec数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return
	 */
	private RskAppoRecVO getRequestParamForRskAppoRec(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String cstId = request.getParameter("cstId");//客户ID
		String collectUsrId = request.getParameter("collectUsrId");//催收员ID
		String appoDt = request.getParameter("appoDt");//预约时间
		String buTypCd = request.getParameter("buTypCd");//业务类型：1.逾期催收 2.租金提醒
		String appoStsCd = request.getParameter("appoStsCd");//预约状态
		String ids=request.getParameter("ids");//客户+支付表Id

		//验证参数并赋值
		RskAppoRecVO entity = new RskAppoRecVO();
		if(StringUtils.isNotEmpty(cstId)){
			entity.setCstId(Long.valueOf(cstId));//客户ID
		}
		if(StringUtils.isNotEmpty(collectUsrId)){
			entity.setCstId(Long.valueOf(collectUsrId));//催收员ID
		}
		if(StringUtils.isNotEmpty(collectUsrId)){
			entity.setAppoDt(DateUtils.formatStringToDate(appoDt,DateUtils.YYYY_MM_DD));//预约时间
		}
		entity.setBuTypCd(buTypCd);//业务类型：1.逾期催收 2.租金提醒
		if(StringUtils.isBlank(buTypCd)){
			entity.setBuTypCd("1");//业务类型：1.逾期催收 2.租金提醒
		}
		entity.setAppoStsCd(appoStsCd);//预约状态

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		}

		return entity;
	}

	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return
	 */
	private List<RskAppoRecVO> getRequestParamForAppoRec(HttpServletRequest request) throws BaseException{
		String appoDt = request.getParameter("appoDt");//预约时间
		String ids=request.getParameter("ids");//客户+支付表Id
		String buTypCd=request.getParameter("buTypCd");
		List<RskAppoRecVO> voList=null;
		//验证参数并赋值
		RskAppoRecVO entity = null;
		if(StringUtils.isBlank(appoDt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择预约时间.");
		}
		if(StringUtils.isNotBlank(ids)){
			List<Map> list= JSON.parseArray(ids,Map.class);
			if(CollectionUtils.isNotEmpty(list)){
				voList=new ArrayList<>(list.size());
				for(Map map:list){
					entity = new RskAppoRecVO();
					entity.setCstId(Long.valueOf(String.valueOf(map.get("cstId"))));
					entity.setPaySchId(Long.valueOf(String.valueOf(map.get("paySchId"))));
					entity.setBuTypCd(buTypCd);
					entity.setAppoDt(DateUtils.formatStringToDate(appoDt,DateUtils.YYYY_MM_DD));//预约时间
					entity.setCollectUsrId(CurrentThreadContext.getCurrentUserId());
					voList.add(entity);
				}
			}
		}else{
			BaseLogUtils.error(logger,"getRequestParamForAppoRec","未找到预约客户支付表信息");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择预约客户支付表.");
		}

		return voList;
	}
}